package com.openlogic.logic.listener;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.noear.solon.annotation.Inject;
import org.noear.solon.cloud.CloudEventHandler;
import org.noear.solon.cloud.annotation.CloudEvent;
import org.noear.solon.cloud.model.Event;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson2.JSON;
import com.mybatisflex.core.query.QueryWrapper;
import com.openlogic.datasource.api.entity.table.Tables;
import com.openlogic.datasource.api.event.DataDeleteEventModel;
import com.openlogic.logic.mapper.datasource.DataColumnMapper;
import com.openlogic.logic.mapper.datasource.DataTableMapper;

/**
 * @ClassName: DataDeleteEventListener
 * @Description: 元数据缓存事件监听
 * @author weiyongpeng
 * @date 2024年11月10日 下午6:15:52
 */
@CloudEvent(topic = "data.delete.event", group = "delete")
public class DataDeleteEventListener  implements CloudEventHandler{

	private static final Logger logger = LoggerFactory.getLogger(DataDeleteEventListener.class);

	@Inject
	private DataTableMapper metadataTableDao;

	@Inject
	private DataColumnMapper metadataColumnDao;

	@Override
	public boolean handle(Event event) throws Throwable {
		DataDeleteEventModel dataDeleteEventModel = JSON.parseObject(event.content(),DataDeleteEventModel.class);
		if (StringUtils.isNotEmpty(dataDeleteEventModel.getId()) && ObjectUtils.isEmpty(dataDeleteEventModel.getIds())) {
			metadataTableDao.deleteByQuery(
					QueryWrapper.create().where(Tables.dataTable.sourceId.eq(dataDeleteEventModel.getId())));
			metadataColumnDao.deleteByQuery(
					QueryWrapper.create().where(Tables.dataColumn.sourceId.eq(dataDeleteEventModel.getId())));
		} else if(StringUtils.isEmpty(dataDeleteEventModel.getId()) && ObjectUtils.isNotEmpty(dataDeleteEventModel.getIds())) {
			metadataTableDao.deleteByQuery(
					QueryWrapper.create().where(Tables.dataTable.sourceId.in(dataDeleteEventModel.getIds())));
			metadataColumnDao.deleteByQuery(QueryWrapper.create()
					.where(Tables.dataColumn.sourceId.in(dataDeleteEventModel.getIds())));
		}
		logger.info("<<<<<事件处理完毕，删除成功>>>>>");
		return true;
	}

}
